using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurretBall:Mob {

	MobProjectile projectile;
	[SerializeField] ProjectileData toShoot;

	protected override void Start() {
		base.Start();
		projectile=GetComponent<MobProjectile>();
		ProjectileEventHelper.firing.SubscribeSingleShooterProjectile(projectile,Projectile_Firing);
	}

	protected override void OnDestroy() {
		base.OnDestroy();
		ProjectileEventHelper.firing.UnsubscribeSingleShooterProjectile(projectile,Projectile_Firing);
	}

	void Projectile_Firing(object _sender,ProjectileEventArgs e) {
		Projectile sender = _sender as Projectile;
		if(sender.data!=projectile.data) return;

		Projectile.CreateWithStat(
			toShoot,
			sender.transform.position,
			(Angle)sender.forward,
			projectile.shooterMob,
			projectile.shooterWeapon,
			projectile,
			sender.stat.consumedAmmo,
			sender.stat,
			null
		);

		sender.transform.position=new Vector3(9999999,9999999);
		Destroy(sender.gameObject);

	}

	float timeAfterShoot;
	protected override void StateIdle() {
		if(stateTime<1.5f) targetVelocity=projectile.velocity;
		else targetVelocity=Vector2.zero;
		timeAfterShoot+=Time.deltaTime;
		if(timeAfterShoot>0.2f) {
			timeAfterShoot-=0.2f;

			Mob targetMob = Utility.FindNearestMob(projectile.transform.position,100,(Mob mob) => (
				mob&&
				FactionManager.GetRelation(faction,mob.faction)<0&&
				Utility.IfLineOfSight(projectile.transform.position,mob)
			));
			Vector2 shootVector = Random.insideUnitCircle;
			if(targetMob) shootVector=targetMob.position-position;
			shootVector.Normalize();
			Projectile.Create(
				toShoot,
				position+shootVector*0.2f,
				(Angle)shootVector,
				projectile,
				x => {
					x.stat.timeTotal.AddMultiply(0.1f,float.MaxValue);
				},
				projectile.stat
			);

		}

	}

}
